package com.util;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.servlet.http.HttpServletRequest;

/**
 * 根据IP地址获取详细的地域信息
 * 
 * @project:personGocheck
 * @class:AddressUtils.java
 * @author:heguanhua E-mail:37809893@qq.com
 * @date：Nov 14, 2012 6:38:25 PM
 */
public class CityUtil {
	private static CityUtil cu;
	public static CityUtil getIns()
	{
		if(cu==null)cu=new CityUtil();
		return cu;
	}
	
	 /**
     * 获取Ip地址
     * @param request
     * @return
     */
    public static String getIpAdrress(HttpServletRequest request) {
        String Xip = request.getHeader("X-Real-IP");
        String XFor = request.getHeader("X-Forwarded-For");
        if(StrKit.notBlank(XFor) && !"unKnown".equalsIgnoreCase(XFor)){
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = XFor.indexOf(",");
            if(index != -1){
                return XFor.substring(0,index);
            }else{
                return XFor;
            }
        }
        XFor = Xip;
        if(StrKit.notBlank(XFor) && !"unKnown".equalsIgnoreCase(XFor)){
            return XFor;
        }
        if (StrKit.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("Proxy-Client-IP");
        }
        if (StrKit.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StrKit.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StrKit.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StrKit.isBlank(XFor) || "unknown".equalsIgnoreCase(XFor)) {
            XFor = request.getRemoteAddr();
        }
        return XFor;
    }

	/**
	 * 根据IP查询地址
	 * @param content 即为IP地址
	 * @return
	 * @throws UnsupportedEncodingException
	 */
	public String getAddresses(String content) {
		// 这里调用pconline的接口
		String urlStr = "http://ip.taobao.com/service/getIpInfo.php";
		// 从http://whois.pconline.com.cn取得IP所在的省市区信息
		String returnStr = this.getResult(urlStr, "ip="+content, "utf-8");
		return returnStr;
	}

	/**
	 * HTTP post数据
	 * @param urlStr
	 *            请求的地址
	 * @param content
	 *            请求的参数 格式为：name=xxx&pwd=xxx
	 * @param encoding
	 *            服务器端请求编码。如GBK,UTF-8等
	 * @return
	 */
	private String getResult(String urlStr, String content, String encoding) {
		URL url = null;
		HttpURLConnection connection = null;
		try {
			url = new URL(urlStr);
			connection = (HttpURLConnection) url.openConnection();// 新建连接实例
			connection.setConnectTimeout(2000);// 设置连接超时时间，单位毫秒
			connection.setReadTimeout(2000);// 设置读取数据超时时间，单位毫秒
			connection.setDoOutput(true);// 是否打开输出流 true|false
			connection.setDoInput(true);// 是否打开输入流true|false
			connection.setRequestMethod("POST");// 提交方法POST|GET
			connection.setUseCaches(false);// 是否缓存true|false
			connection.connect();// 打开连接端口
			DataOutputStream out = new DataOutputStream(
					connection.getOutputStream());// 打开输出流往对端服务器写数据
			out.writeBytes(content);// 写数据,也就是提交你的表单 name=xxx&pwd=xxx
			out.flush();// 刷新
			out.close();// 关闭输出流
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					connection.getInputStream(), encoding));// 往对端写完数据对端服务器返回数据
			// ,以BufferedReader流来读取
			StringBuffer buffer = new StringBuffer();
			String line = "";
			while ((line = reader.readLine()) != null) {
				buffer.append(line);
			}
			reader.close();
			return buffer.toString();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (connection != null) {
				connection.disconnect();// 关闭连接
			}
		}
		return null;
	}

	/**
	 * unicode 转换成 中文
	 * 
	 * @author fanhui 2007-3-15
	 * @param theString
	 * @return
	 */
	public static String decodeUnicode(String theString) {
		char aChar;
		int len = theString.length();
		StringBuffer outBuffer = new StringBuffer(len);
		for (int x = 0; x < len;) {
			aChar = theString.charAt(x++);
			if (aChar == '\\') {
				aChar = theString.charAt(x++);
				if (aChar == 'u') {
					int value = 0;
					for (int i = 0; i < 4; i++) {
						aChar = theString.charAt(x++);
						switch (aChar) {
						case '0':
						case '1':
						case '2':
						case '3':
						case '4':
						case '5':
						case '6':
						case '7':
						case '8':
						case '9':
							value = (value << 4) + aChar - '0';
							break;
						case 'a':
						case 'b':
						case 'c':
						case 'd':
						case 'e':
						case 'f':
							value = (value << 4) + 10 + aChar - 'a';
							break;
						case 'A':
						case 'B':
						case 'C':
						case 'D':
						case 'E':
						case 'F':
							value = (value << 4) + 10 + aChar - 'A';
							break;
						default:
							throw new IllegalArgumentException(
									"Malformed      encoding.");
						}
					}
					outBuffer.append((char) value);
				} else {
					if (aChar == 't') {
						aChar = '\t';
					} else if (aChar == 'r') {
						aChar = '\r';
					} else if (aChar == 'n') {
						aChar = '\n';
					} else if (aChar == 'f') {
						aChar = '\f';
					}
					outBuffer.append(aChar);
				}
			} else {
				outBuffer.append(aChar);
			}
		}
		return outBuffer.toString();
	}
	
	/**
	 * 根据省取地市
	 * @param province
	 * @return
	 */
	public static String getCityByProvince(String province)
	{
		if(StrKit.isBlank(province))return "哈尔滨市";
		String city="";
		if(province.equals("黑龙江省")||province.equals("黑龙江"))city="哈尔滨市";
		else if(province.equals("云南省")||province.equals("云南"))city="昆明市";
		else if(province.equals("吉林省")||province.equals("吉林"))city="长春市";
		else if(province.equals("安徽省")||province.equals("安徽"))city="合肥市";
		else if(province.equals("山东省")||province.equals("山东"))city="济南市";
		else if(province.equals("山西省")||province.equals("山西"))city="太原市";
		else if(province.equals("广东")||province.equals("广东"))city="广州市";
		else if(province.equals("江苏省")||province.equals("江苏"))city="南京市";
		else if(province.equals("江西省")||province.equals("江西"))city="南昌市";
		else if(province.equals("河北省")||province.equals("河北"))city="石家庄市";
		else if(province.equals("河南省")||province.equals("河南"))city="郑州市";
		else if(province.equals("浙江省")||province.equals("浙江"))city="杭州市";
		else if(province.equals("海南省")||province.equals("海南"))city="海口市";
		else if(province.equals("湖北省")||province.equals("湖北"))city="武汉市";
		else if(province.equals("湖南省")||province.equals("湖南"))city="长沙市";
		else if(province.equals("甘肃省")||province.equals("甘肃"))city="兰州市";
		else if(province.equals("福建省")||province.equals("福建"))city="福州市";
		else if(province.equals("四川省")||province.equals("四川"))city="成都市";
		else if(province.equals("贵州省")||province.equals("贵州"))city="贵阳市";
		else if(province.equals("青海省")||province.equals("青海"))city="西宁市";
		else if(province.equals("辽宁省")||province.equals("辽宁"))city="沈阳市";
		else if(province.equals("陕西省")||province.equals("陕西"))city="西安市";
		
		
		return city;
	}
	

	// 测试
	public static void main(String[] args) {
		CityUtil addressUtils = new CityUtil();
		// 测试ip 219.136.134.157 中国=华南=广东省=广州市=越秀区=电信
		String ip = "123.165.222.1";
		String address = "";
		address = addressUtils.getAddresses(ip);
		System.out.println(address);
		// 输出结果为：广东省,广州市,越秀区
	}
}